<template>
  <div class="department-tree">
    <p class="aside-title">
      显示子部门：
      <el-switch
        v-model="listQuery.isChildUser"
        active-color="#409EFF"
        active-value="1"
        inactive-value="2"
        @change="handleChange"
      ></el-switch>
    </p>
    <el-tree
      :data="tableData"
      :props="defaultProps"
      :expand-on-click-node="false"
      accordion
      node-key="id"
      style="width: 260px; height: 630px; overflow-x: auto"
      @node-click="handleNodeClickDep1"
      :default-expanded-keys="expandedArr"
    ></el-tree>
  </div>
</template>
<script>
export default {
  data() {
    return {
      listQuery: {
        deptId: '',
        isChildUser: '1',
      },
      tableData: [],
      expandedArr: [],
      defaultProps: {
        children: 'childList',
        label: 'name',
      },
    }
  },
  props: ['deptData'],
  watch: {
    deptData: {
      immediate: true,
      handler(v) {
        if (v.length == 0) return
        this.init(v)
      },
    },
  },
  mounted() {},
  methods: {
    //查询部门
    async init(deptData) {
      let data = JSON.parse(JSON.stringify(deptData))
      let { userType, deptFullData } = this.$store.getters
      if (userType == 1) {
        //超管
        this.tableData = data
      } else {
        //普通管理员
        if (!data.length || data.hasOwnProperty('childList')) return
        let fullDept = data[0].childList
        if (
          deptFullData.hasOwnProperty('childList') &&
          deptFullData.childList.length
        ) {
          let schoolDept = deptFullData.childList[0].id
          this.tableData = fullDept.filter((v) => v.id == schoolDept)
        }
      }
      if (this.tableData.length) {
        this.expandedArr.push(this.tableData[0].id)
      }
      this.listQuery.deptId =
        this.tableData.length > 0 ? this.tableData[0].id : ''
      this.$bus.$emit('refreshUserList', this.listQuery)
    },
    // 选中上一级单位
    handleNodeClickDep1(val) {
      this.treeName1 = val.name
      this.treeFlag1 = false
      this.listQuery.deptId = val.id
      this.$bus.$emit('refreshUserList', this.listQuery)
    },
    handleChange() {
      this.$bus.$emit('refreshUserList', this.listQuery)
    },
  },
}
</script>
<style scoped lang="scss">
.department-tree {
  padding: 0px 10px 10px 10px;
  background: #f5f7fa;
  .aside-title {
    padding: 5px 0;
  }
}
</style>